#include "myclientsocket.h"
#include <QHostAddress>

#include <QDebug>
#include <QJsonObject>
#include <QJsonDocument>
#include "stdshared.h"

MyClientSocket::MyClientSocket(QObject *parent) : QObject(parent)
{
    m_socket =new QTcpSocket;
    //连接服务器
    connect(m_socket,&QTcpSocket::connected,this,[=]()
    {

        qDebug()<<"连接服务器成功"<<endl;
    });

    connect(m_socket,&QTcpSocket::readyRead,this,&MyClientSocket::handleReadSlot);
}

void MyClientSocket::connectToServer(const QString &ip, int port)
{
    m_socket->connectToHost(QHostAddress(ip),port);
    m_ip=ip;
    m_port=port;
}

int MyClientSocket::writeBytes(const QByteArray &data)
{
    //先发数据包头
    size_t dataSize=data.size();
    m_socket->write((const char *)&dataSize,sizeof(size_t));
    //再发数据本身
    m_socket->write(data);
}

void MyClientSocket::handleReadSlot()
{
    qDebug()<<"准备接收数据"<<endl;
    //先读数据的包头
    m_buffer.append(m_socket->readAll());
    while(m_buffer.size() >= sizeof(size_t))
    {
        size_t size;
        memcpy(&size,m_buffer.data(),sizeof(size_t));
        if(m_buffer.size()<size+sizeof(size_t))
        {
            break ;
        }
        //缓冲区存在size字节
        emit dataRecv(m_buffer.mid(sizeof(size_t),size));
        m_buffer.remove(0,sizeof(size_t)+size);
    }

}
